#!/usr/bin/python
# -*- coding: utf-8 -*-

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################


from pylot.core import (Collection, Path, Utils, uprint, LANG,
                                CommandGroup, Book)

def generate_pro_file(plugin_path, lang, ui_dirs=[], tr_=tr_):
  u"""
  if ui_dir is None, search in plugin_path directory
  """
  plugin_path = Path(plugin_path)
  i18n = Path(plugin_path, u'i18n')
  ui_dirs = [Path(p) for p in ui_dirs] + [plugin_path]

  ui_files = []
  for ui_dir in ui_dirs :
    ui_files += [i18n.relpathto(f) for f in ui_dir.listdir(u'*.ui')]

  if ui_files :
    content = """
# WARNING! All changes made in this file will be lost!

CODECFORTR = UTF-8
CODECFORSRC = UTF-8

FORMS = %s

TRANSLATIONS = %s.ts
    """ % ('\\\n        '.join(ui_files), lang)
    uprint(tr_(u'writing code.pro file\n'))
    pro_file = open(Path(plugin_path, u'i18n', u'code.pro'), u'w')
    pro_file.write(content)
    pro_file.close()

def extract_collection_translation(plugin_path, adds_file, tr_=tr_):
  u"""
  Creates a python file recognized bye i18n tools like gettext or 
  pybabel to allow to translate Collection and Book files :

  Extracts all aliases and tooltips from Collection or Book csv files.
  Extracted strings are saved as unicode strings in python file "i18n_adds.py".
  """
  path = Path(plugin_path)
  i18n_file = Utils.writefile(adds_file, security=u'force')
  i18n_file.write(u'# -*- coding: utf-8 -*-\n')
  i18n_file.write(u'# WARNING! All changes made in this file will be lost! \n\n')

  for csvfile in path.walkfiles(u'*.csv') :
    uprint(tr_(u'extracting messages from %(FILE)s\n') % dict(FILE=csvfile))
    collection = Collection()
    try :
      collection.upFromFile(csvfile, u'csv')
    except UnboundLocalError :
      try :
        collection = Book()
        collection.upFromFile(csvfile, u'csv')
      except :
        datatype = u'unknown'
      else :
        datatype = u'book'
    else :
      datatype = u'collection'

    if datatype == u'collection' :
      i18n_file.write(u'\n# Collection file: %s\n' % adds_file.parent.relpathto(csvfile))
      for book in collection.values() :
        for datum in book.values() :
          for text_type in ('alias', 'tooltip') :
            datum_text = getattr(datum, text_type)
            if datum_text :
              datum_text = datum_text.replace(u'"', u'\\"')
              text = u'tr_(u"%s")' % datum_text
              i18n_file.write(text)
              text = u' # Book: %s, Opt: %s (%s)\n' % (book.name, datum.name, text_type)
              i18n_file.write(text)
    elif datatype == u'book':
      i18n_file.write(u'\n# Book file: %s\n' % csvfile)
      for datum in collection.values() :
        for text_type in ('alias', 'tooltip') :
          datum_text = getattr(datum, text_type)
          if datum_text :
            datum_text = datum_text.replace(u'"', u'\\"')
            text = u'tr_(u"%s")' % datum_text
            i18n_file.write(text)
            text = u' # Opt: %s (%s)\n' % (datum.name, text_type)
            i18n_file.write(text)

  i18n_file.close()

def _arrange_path_lang(plugin_path, lang):
  if lang is None :
    lang = LANG
  path = Path(plugin_path).abspath()
  return path, lang

def _cg_extract_translation(plugin_path, additional_paths=[], tr_=tr_):
  path, lang = _arrange_path_lang(plugin_path, None)
  i18n_adds = Path(path, u'i18n', u'i18n_adds.py')
  rel_add_paths = []
  for p in additional_paths :
    new = Path(path, u'i18n').relpathto(p)
    rel_add_paths.append(new)

  cg = CommandGroup(u'extractTranslation')
  cg.working_directory = path
  cg.addShellCmd(u'mkdir', [u'-p', u'i18n'])
  cg.working_directory = Path(path, u'i18n')
  cg.addPythonCmd(extract_collection_translation,
                  args=[path, i18n_adds], kargs={'tr_':tr_},
                  cmd_id=u'extractCollectionStrings')
  cg.addShellCmd(u'pybabel',
    [u'extract',
    u'--keyword="tr_"',
    u'-o ./msg.pot', u'--add-comments="l10n-note:"',
    u' '.join([u'../'] + [unicode(p) for p in rel_add_paths])])
  return cg

def cg_compile_translation(plugin_path, lang, tr_=tr_):
  path, lang = _arrange_path_lang(plugin_path, lang)

  cg = CommandGroup(u'compileTranslation', alias=u'Compile Translation',
                    category=u'Compile %s' % lang)
  cg.working_directory = Path(path, u'i18n')
  cg.addShellCmd(u'mkdir',
    [u'-p', u'%s/LC_MESSAGES' % lang])
  cg.addShellCmd(u'pybabel',
    [u'compile', u'--domain=%s' % path.name,
     u'-i ./%s.po' % lang,
     u'-d .',
     u'--locale=%s' % lang])
  cg.addPythonCmd(generate_pro_file,
                  args=[path, lang], kargs={'tr_':tr_},
                  cmd_id=u'generateProFile')
  cg.addShellCmd(u'lrelease', [u'-compress', u'code.pro'])
  return cg


def cg_update_translation(plugin_path, lang, additional_paths=[], ui_dirs=[],
                          tr_=tr_):
  path, lang = _arrange_path_lang(plugin_path, lang)

  cg = _cg_extract_translation(path, additional_paths, tr_=tr_)
  cg.group_id = u'updateTranslation'
  cg.alias = u'Update translation'
  cg.category = u'Update %s' % lang
  cg.addShellCmd(u'pybabel',
    [u'update', u'--domain=%s' % path.name,
     u'-i ./msg.pot',
     u'-d .',
     u'--locale=%s' % lang,
     u'-o ./%s.po' % lang])
  cg.addPythonCmd(generate_pro_file,
                  args=[path, lang, ui_dirs], kargs=dict(tr_=tr_),
                  cmd_id=u'generateProFile')
  cg.addShellCmd(u'lupdate', [u'code.pro'])

  uprint(cg.prettyPrint())
  return cg

def cg_init_translation(plugin_path, lang, additional_paths=[], tr_=tr_):
  path, lang = _arrange_path_lang(plugin_path, lang)

  cg = _cg_extract_translation(path, additional_paths, tr_=tr_)
  cg.group_id = u'initTranslation'
  cg.alias = u'Init translation'
  cg.category = u'Init %s' % lang
  cg.addShellCmd(u'pybabel',
    [u'init', u'--domain=%s' % path.name,
     u'-i ./msg.pot',
     u'-d .',
     u'--locale=%s' % lang,
     u'-o ./%s.po' % lang])
  return cg

if __name__ == '__main__':
  import doctest
  doctest.testmod()
